﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;

namespace  ZX.EHR.Web
{
    public partial class hrImportWorkResult : BasePage
    {
        static string resFileName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            string flag = this.GetStringFromQueryString("flag", "");
            if (flag.Trim() == "save")
            {
                this.SaveData();
            }
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
                return string.Empty;

            FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
            string path = Request.PhysicalApplicationPath + "upload/EHR/";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            resFileName = path + fileInfo.Name;
            uploadedFile.SaveAs(resFileName);

            RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
            string fileLabel = fileInfo.Name;
            string fileLength = uploadedFile.ContentLength / 1024 + "K";
            return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData()
        {
            IList<DataTable> lstImportData = null;
            try
            {
                //读取EXCEL
                //string resFileName = Request.PhysicalApplicationPath + "upload/EHR/" + fileName;
                int LateTime = 0, AdvancedTime = 0;
                decimal LeaveTime = 0, TiaoxiuTime = 0, BinJiaTime = 0, ShiJiaTime = 0, NianJiaTime = 0, HunJiaTime=0;
                decimal SangJiaTime = 0, ChanJiaTime = 0, ChanJianJiaTime = 0, PeiChanJiaTime = 0, GongshanJiaTime = 0, FaDingJiaTime = 0, TripTime = 0, OutwardTime = 0;
                decimal WorkDayOverTime = 0, WeekendOverTime = 0, HolidayOverTime = 0, AbsenceTime = 0;
                string isNormal = "", WkStatus = "", employeeID = "", employeeName = "", employeeCode = "", IsValidate = "N", IsImport = "Y";
                string NoExist = "", NoChildCompanyEmp = "";
                DateTime WorkDate = new DateTime();
                DateTime ImportDate = DateTime.Now;
                int i = 0, iNoExist = 0, iNoChildCompanyEmp = 0;
                string insetsql = @"INSERT INTO wkWorkResult
                       ([ID],[EmployeeID],[WorkDate],[WkStatus],[LateTime],[AdvancedTime],[LeaveTime],[TripTime],[WorkDayOverTime]
                       ,[WeekendOverTime],[HolidayOverTime],[AbsenceTime],[TiaoxiuTime],[BinJiaTime],[ShiJiaTime],[NianJiaTime]
                       ,[HunJiaTime],[SangJiaTime],[ChanJiaTime],[ChanJianJiaTime],[PeiChanJiaTime],[GongshanJiaTime]
                       ,[FaDingJiaTime],[OutwardTime],[StatDate],[IsValidate],[IsEdite],[IsImport],[ImportDate]) VALUES(NEWID(),'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}',
                       '{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}','{26}','{27}')";

                if (resFileName != "")
                {
                    lstImportData = new List<DataTable>();
                    DbSql dbsql = new DbSql();
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);
                    //取得操作者所属分公司人员
                    workTimeAjax workTimeAjax = new workTimeAjax();
                    IList<hrEmployee> lstEmp = workTimeAjax.GetChildCompanyEmpInfo();
                    if (lstEmp == null)
                    {
                        HttpContext.Current.Response.Write("3");//"您非分公司人员，考勤记录不允许导入！"
                        return;
                    }

                    if (dtExcel != null && dtExcel.Rows.Count > 0)
                    {
                        lstImportData.Add(dtExcel);
                    }
                    foreach (DataTable dt in lstImportData)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            string empCode = dr["员工编号"].ToString().Trim();
                            //工号为空则不再导入后续行
                            if (empCode == "")
                            {
                                break;
                            }
                            //工号必须是5位
                            if (empCode.Length != 5)
                            {
                                continue;
                            }

                            Dictionary<string, string> dicEmpInfo = GetEmpInfos(empCode);
                            bool isChildCompanyEmp = false;
                            if (dicEmpInfo.Count > 0)
                            {
                                employeeID = dicEmpInfo["EmployeeID"];
                                employeeName = dicEmpInfo["EmployeeName"];
                                employeeCode = dicEmpInfo["EmployeeCode"];
                                //操作者只能导入所属分公司人员
                                foreach (hrEmployee item in lstEmp)
                                {
                                    if (item.ID.ToString() == employeeID)
                                    {
                                        isChildCompanyEmp = true;
                                        break;
                                    }
                                }

                                if (!isChildCompanyEmp)
                                {
                                    iNoChildCompanyEmp++;
                                    if (NoChildCompanyEmp.IndexOf(empCode) < 0)
                                    {
                                        NoChildCompanyEmp += empCode + ",";
                                    }
                                }
                            }
                            else
                            {
                                iNoExist++;
                                if (NoExist.IndexOf(empCode) < 0)
                                {
                                    NoExist += empCode + ",";
                                }
                            }

                            if(isChildCompanyEmp)
                            {
                                DateTime.TryParse(dr["工作日"].ToString(), out WorkDate);
                                isNormal = dr["正常出勤"].ToString().Trim();
                                int.TryParse(dr["迟到(m)"].ToString(), out LateTime);
                                int.TryParse(dr["早退(m)"].ToString(), out AdvancedTime);
                                decimal.TryParse(dr["病假(h)"].ToString(), out BinJiaTime);
                                decimal.TryParse(dr["事假(h)"].ToString(), out ShiJiaTime);
                                decimal.TryParse(dr["年假(h)"].ToString(), out NianJiaTime);
                                decimal.TryParse(dr["婚假(h)"].ToString(), out HunJiaTime);
                                decimal.TryParse(dr["丧假(h)"].ToString(), out SangJiaTime);
                                decimal.TryParse(dr["产假(h)"].ToString(), out ChanJiaTime);
                                decimal.TryParse(dr["产检假(h)"].ToString(), out ChanJianJiaTime);
                                decimal.TryParse(dr["陪产假(h)"].ToString(), out PeiChanJiaTime);
                                decimal.TryParse(dr["工伤假(h)"].ToString(), out GongshanJiaTime);
                                decimal.TryParse(dr["法定假(h)"].ToString(), out FaDingJiaTime);
                                decimal.TryParse(dr["调休(h)"].ToString(), out TiaoxiuTime);
                                decimal.TryParse(dr["出差(h)"].ToString(), out TripTime);
                                decimal.TryParse(dr["缺勤(h)"].ToString(), out AbsenceTime);
                                decimal.TryParse(dr["外出(h)"].ToString(), out OutwardTime);
                                decimal.TryParse(dr["工作日加班(h)"].ToString(), out WorkDayOverTime);
                                decimal.TryParse(dr["周末加班(h)"].ToString(), out WeekendOverTime);
                                decimal.TryParse(dr["节假日加班(h)"].ToString(), out HolidayOverTime);
                                //请假总时长
                                LeaveTime = BinJiaTime + ShiJiaTime + NianJiaTime + HunJiaTime + SangJiaTime + ChanJiaTime + ChanJianJiaTime + PeiChanJiaTime + GongshanJiaTime + FaDingJiaTime + TiaoxiuTime + TripTime + OutwardTime;
                                WkStatus = "";
                                if (isNormal == "是")
                                {
                                    WkStatus = "正常出勤";
                                }
                                else
                                {
                                    if (LateTime > 0)
                                    {
                                        WkStatus += "迟到,";
                                    }
                                    if (AdvancedTime > 0)
                                    {
                                        WkStatus += "早退,";
                                    }
                                    if (BinJiaTime > 0)
                                    {
                                        WkStatus += "病假,";
                                    }
                                    if (ShiJiaTime > 0)
                                    {
                                        WkStatus += "事假,";
                                    }
                                    if (NianJiaTime > 0)
                                    {
                                        WkStatus += "年假,";
                                    }
                                    if (HunJiaTime > 0)
                                    {
                                        WkStatus += "婚假,";
                                    }
                                    if (SangJiaTime > 0)
                                    {
                                        WkStatus += "丧假,";
                                    }
                                    if (ChanJiaTime > 0)
                                    {
                                        WkStatus += "产假,";
                                    }
                                    if (ChanJianJiaTime > 0)
                                    {
                                        WkStatus += "产检假,";
                                    }
                                    if (PeiChanJiaTime > 0)
                                    {
                                        WkStatus += "陪产假,";
                                    }
                                    if (GongshanJiaTime > 0)
                                    {
                                        WkStatus += "工作假,";
                                    }
                                    if (FaDingJiaTime > 0)
                                    {
                                        WkStatus += "法定假,";
                                    }
                                    if (TiaoxiuTime > 0)
                                    {
                                        WkStatus += "调休,";
                                    }
                                    if (TripTime > 0)
                                    {
                                        WkStatus += "出差,";
                                    }
                                    if (AbsenceTime > 0)
                                    {
                                        WkStatus += "缺勤,";
                                    }
                                    if (OutwardTime > 0)
                                    {
                                        WkStatus += "外出,";
                                    }
                                    if (WorkDayOverTime > 0 || WeekendOverTime > 0 || HolidayOverTime > 0)
                                    {
                                        WkStatus += "加班,";
                                    }
                                    if (WkStatus != "")
                                    {
                                        WkStatus = WkStatus.Substring(0, WkStatus.Length - 1);
                                    }
                                }
                                //缺勤时长应该加上请假时长
                                AbsenceTime = AbsenceTime + LeaveTime;
                                string tempsql = string.Format(insetsql, new Guid(employeeID), WorkDate, WkStatus, LateTime, AdvancedTime, LeaveTime, TripTime,WorkDayOverTime, WeekendOverTime, HolidayOverTime, AbsenceTime, TiaoxiuTime, BinJiaTime, ShiJiaTime, NianJiaTime, HunJiaTime, SangJiaTime, ChanJiaTime, ChanJianJiaTime, PeiChanJiaTime, GongshanJiaTime, FaDingJiaTime, OutwardTime, DateTime.Now, IsValidate, 'N', IsImport, ImportDate);
                                if (IsCanImport(employeeID, WorkDate))
                                {
                                    dbsql.ExecuteScalar(tempsql);
                                 i++;
                                }
                            }
                        }
                    }
                    HttpContext.Current.Response.Write("1|" + i.ToString() + "|" + iNoExist.ToString() + "|" + NoExist + "|" + iNoChildCompanyEmp.ToString()+ "|" + NoChildCompanyEmp + "|OK");
                }
                else
                {
                    HttpContext.Current.Response.Write("2");//文件未上传
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
                throw ex;
            }
            finally
            {
                if (lstImportData != null)
                {
                    lstImportData.Clear();
                }
                resFileName = "";
            }
        }

        /// <summary>
        /// 根据导入的工号，匹配员工信息
        /// </summary>
        /// <param name="importEmpCode"></param>
        /// <returns></returns>
        protected Dictionary<string, string> GetEmpInfos(string importEmpCode)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("SUBSTRING(EmployeeCode,3,10)='{0}'", importEmpCode);
            ZX.EHR.Library.hrEmployee hrEmployee = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            if (hrEmployee != null)
            {
                dic.Add("EmployeeID", hrEmployee.ID.ToString());
                dic.Add("EmployeeCode", hrEmployee.EmployeeCode);
                dic.Add("EmployeeName", hrEmployee.CName);
            }
            return dic;
        }

        /// <summary>
        /// 是否可以写导入数据
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="cardDate"></param>
        /// <returns></returns>
        protected bool IsCanImport(string employeeId, DateTime workDate)
        {
            wkWorkResult instance = ZX.Common.Globals.getEntity("wkWorkResult") as wkWorkResult;
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
            DbSql dbsql = new DbSql();
            bool isOk = false; //是否可以写入
            string delsql = "delete from wkWorkResult where {0} ";
            string condition = string.Format("EmployeeID='{0}' and WorkDate='{1}' ", employeeId, workDate.ToString("yyyy-MM-dd"));
            dbsql.ExecuteScalar(string.Format(delsql, condition));
            isOk = true;
            //wkWorkResult wkWorkResult = bll.GetEntityByCondition(condition) as wkWorkResult;
            //if (wkWorkResult != null)
            //{
            //    ////存在记录，则进一步判断,已经确认或手工更改过的不应该被导入修改
            //    //if (wkWorkResult.IsValidate == "Y" || wkWorkResult.IsEdite == "Y")
            //    //{
            //    //    isOk = false;
            //    //}
            //    //else
            //    //{
            //        //未确认或未手工更改过的则可以被导入修改
            //        dbsql.ExecuteScalar(string.Format(delsql, condition));
            //        isOk = true;
            //    //}
            //}
            //else
            //{
            //    isOk = true;
            //}
            return isOk;
        }
    }
}